//
//  KuaixunModel.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/2.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON

class KuaixunModel: NSObject , HandyJSON {

    var isRead = false
    
    var modelId:String?
    
    var title:String?
    
    var favourateCount:String?

    var date: String?
    
    override required init() {
        
    }
    
    func mapping(mapper: HelpingMapper) {
        mapper.specify(property:&modelId, name: "id")
        mapper.specify(property:&title, name: "content")
        mapper.specify(property:&favourateCount,name: "praiseNum")
        mapper.specify(property:&date, name: "pushtime")
    }
    
    func getTime() -> String{
        return self.date!
    }

    static var readList:[String]?
    func updateIsRead() -> Void {
        guard let reads = KuaixunModel.readList else {
            self.isRead = false
            return
        }
        if  reads.count == 0{
            self.isRead = false
            return
        }
        let sameIds = reads.filter{ kxid in
            return self.modelId! == kxid
        }

        self.isRead = (sameIds.count > 0)
    }
    
    func setRead() {
        self.isRead = true
        if KuaixunModel.readList?.firstIndex(of: self.modelId!) == nil {
            KuaixunModel.readList?.append(self.modelId!)
            KuaixunModel.persistentReadList()
        }
        
    }
    
    static func readListFromPersistence(){
        let readListStr = UserDefaults.standard.string(forKey: "ssssReadList")
        KuaixunModel.readList = readListStr?.components(separatedBy: ",")
        if KuaixunModel.readList == nil {
            KuaixunModel.readList = [];
        }
    }
    
    static func persistentReadList(){
        guard let reads = KuaixunModel.readList else {
            return
        }
        let result = reads.reduce("") { (sum, nextId) -> String in
            sum + nextId + ","
        }
        UserDefaults.standard.set(result, forKey: "ssssReadList")
    }
    
    static var loveList : [String]?
    func isLoved() -> Bool{
        if KuaixunModel.loveList == nil {
            let lovesStr = UserDefaults.standard.string(forKey: "ssssLoveList")
            KuaixunModel.loveList = lovesStr?.components(separatedBy: ",")
        }
        let lovedIds = KuaixunModel.loveList?.filter(){ (kxid) -> Bool in
             return self.modelId! == kxid
        }
        return (lovedIds?.count)! > 0
    }
    
    func setLoved(_ isLoved: Bool) {
        if KuaixunModel.loveList == nil {
            let lovesStr = UserDefaults.standard.string(forKey: "ssssLoveList")
            KuaixunModel.loveList = lovesStr?.components(separatedBy: ",")
        }
        KuaixunModel.loveList?.append(self.modelId!)
        UserDefaults.standard.set(KuaixunModel.loveList!, forKey: "ssssLoveList")
    }

}
